<template>
  <div>
    <div class="banner linear-bg-blue">
      <div class="top">
        <img :src="account.logo" mode="aspectFill" class="logo">
        <span class="shop-name">{{account.shopName}}</span>
        <picker
          v-model="searchDate"
          class="date-filter-picker"
          mode="date"
          :end="currentDate"
          disabled
          @change="handleDateChange"
        >
          <span class="value">{{searchDate}}</span>
        </picker>
      </div>
      <div class="panel">
        <div v-for="item in blockList" :key="item.key" class="block">
          <p class="title">
            <img :src="item.icon" mode="aspectFit" class="small-icon">
            {{item.name}}
          </p>
          <span>{{countForm[item.key]}}</span>
        </div>
      </div>
    </div>
    <div class="filter">
      <picker
        v-model="yearIdx"
        class="filter-picker"
        :range="yearList"
        range-key="label"
        @change="handleYearChange"
      >
        <span class="value">{{form.year+'年'}}</span>
      </picker>
      <picker
        v-model="stateIdx"
        class="filter-picker"
        :range="stateList"
        range-key="label"
        @change="handleStateChange"
      >
        <span class="value">{{stateList[stateIdx].label}}</span>
      </picker>
    </div>
    <div class="statistics">
      <p class="part">
        订单金额
        <span class="blue">{{orderAmount}}</span>元
      </p>
    </div>
    <div class="chart-wrap">
      <mpvue-echarts
        ref="echarts"
        :echarts="echarts"
        lazyLoad
        :on-init="initChart"
        throttle-touch
      />
    </div>
  </div>
</template>

<script>
import echarts from 'echarts/lib/echarts'
import 'echarts/lib/chart/bar'
import 'echarts/lib/chart/line'
import mpvueEcharts from 'mpvue-echarts'
import { formatTime } from '@/utils'
import {
  SHOP_SALES_COUNT,
  SHOP_RETURN_PENSION_COUNT,
  SHOP_EVALUATION_COUNT,
  SHOP_COLLECTION_COUNT,
  FIND_SHOP_ORDER_PAGE
} from '@/api'
import chartOption from './chart'

let chart = null

export default {
  components: { mpvueEcharts },
  props: {},
  data () {
    return {
      form: { year: '', state: '' },
      yearIdx: 0,
      stateIdx: 3,
      stateList: [
        { value: '0', label: '待付款' },
        { value: '1', label: '待收货' },
        { value: '2', label: '已取消' },
        { value: '3', label: '已收货' },
        { value: '4', label: '退款中' },
        { value: '5', label: '已退款' }
      ],
      echarts,
      salesData: [],
      searchDate: '',
      countForm: {
        memberTotal: 0,
        score: 0,
        collect: 0,
        orderTotal: 0
        // hasReturnAmount: '',
        // notReturnAmount: '',
        // totalReturnAmount: ''
      }
    }
  },
  computed: {
    account () {
      return this.$store.state.account
    },
    yearList () {
      let yearEnd = new Date().getFullYear()
      let arr = []
      for (let index = 0; index < 10; index++) {
        const value = yearEnd - index
        arr.push({ value, label: value + '年' })
      }
      return arr
    },
    currentDate () {
      return formatTime(new Date()).replace(/\s.*$/, '')
    },
    blockList () {
      return [
        {
          name: '会员数',
          key: 'memberTotal',
          icon: '/static/assets/icon/sjfx_hys.png'
        },
        {
          name: '店铺评分',
          key: 'score',
          icon: '/static/assets/icon/sjfx_hpl.png'
        },
        {
          name: '收藏量',
          key: 'collect',
          icon: '/static/assets/icon/sjfx_scl.png'
        },
        {
          name: '订单总数',
          key: 'orderTotal',
          icon: '/static/assets/icon/sjfx_ddzs.png'
        }
      ]
    },
    orderAmount () {
      let amount = 0
      this.salesData.forEach(_ => {
        amount += _.saleAmount
      })
      return amount.toFixed(2)
    }
  },
  watch: {},
  created () {},
  mounted () {},
  onShow () {
    this.initPage()
  },
  methods: {
    handleYearChange (e) {
      let idx = e.target.value
      this.yearIdx = idx
      this.form.year = this.yearList[idx].value
      this.shopSalesCount()
    },
    handleStateChange (e) {
      let idx = e.target.value
      this.stateIdx = idx
      this.form.state = this.stateList[idx].value
      this.shopSalesCount()
    },
    handleDateChange (e) {
      let val = e.target.value
      this.searchDate = val
      // this.shopReturnPensionCount()
    },

    initPage () {
      this.form.yearIdx = 0
      this.form.year = new Date().getFullYear()
      this.form.stateIdx = 3
      this.form.state = '3'
      this.searchDate = this.currentDate

      this.shopSalesCount()
      // this.shopReturnPensionCount()
      this.shopMemberCount()
      this.shopEvaluationCount()
      this.shopCollectionCount()
      this.shopOrderCount()
    },
    initChart (canvas, width, height) {
      chart = echarts.init(canvas, null, { width, height })
      canvas.setChart(chart)

      let option = chartOption

      // 销售额 销售额涨幅 销量 销量涨幅
      let keys = ['saleAmount', 'amountRiseRate', 'saleNum', 'numRiseRate']

      keys.forEach((key, idx) => {
        option.series[idx].data = this.salesData.map(_ => _[key])
      })

      chart.setOption(option)

      return chart
    },
    refreshChart (list) {
      // update chart data
      this.salesData = list
      // redraw chart
      this.$refs.echarts.init()
    },

    shopSalesCount () {
      const vm = this

      let params = {
        shopId: vm.account.shopId,
        ...vm.form
      }

      SHOP_SALES_COUNT(params)
        .then(r => {
          if (r.data.code === '0') {
            let { countShopByMonthList } = r.data.data
            vm.refreshChart(
              countShopByMonthList.sort((a, b) => a.month - b.month)
            )
          } else {
            vm.$toast(r.data.message)
          }
        })
        .catch(e => {
          console.error(e)
        })
    },
    shopReturnPensionCount () {
      const vm = this

      let params = {
        shopId: vm.account.shopId,
        returnDate: vm.searchDate + ' 00:00:00'
      }

      SHOP_RETURN_PENSION_COUNT(params)
        .then(r => {
          if (r.data.code === '0') {
            let {
              hasReturnAmount,
              notReturnAmount,
              totalReturnAmount
            } = r.data.data

            vm.countForm.hasReturnAmount =
              '￥' + hasReturnAmount * (0.01).toFixed(2)
            vm.countForm.notReturnAmount =
              '￥' + notReturnAmount * (0.01).toFixed(2)
            vm.countForm.totalReturnAmount =
              '￥' + totalReturnAmount * (0.01).toFixed(2)
          } else {
            vm.$toast(r.data.message)
          }
        })
        .catch(e => {
          console.error(e)
        })
    },
    shopMemberCount () {
      this.countForm.memberTotal = Math.floor(Math.random() * 100) + '(fake)'
    },
    shopEvaluationCount () {
      const vm = this

      SHOP_EVALUATION_COUNT(vm.account.shopId)
        .then(r => {
          if (r.data.code === '0') {
            vm.countForm.score = r.data.data.shopAssessAvg
          } else {
            vm.$toast(r.data.message)
          }
        })
        .catch(e => {
          console.error(e)
        })
    },
    shopCollectionCount () {
      const vm = this

      SHOP_COLLECTION_COUNT(vm.account.shopId)
        .then(r => {
          if (r.data.code === '0') {
            vm.countForm.collect = r.data.data
          } else {
            vm.$toast(r.data.message)
          }
        })
        .catch(e => {
          console.error(e)
        })
    },
    shopOrderCount () {
      const vm = this

      let params = {
        shopId: vm.account.shopId
      }

      FIND_SHOP_ORDER_PAGE(params, 1, 1)
        .then(r => {
          if (r.data.code === '0') {
            vm.countForm.orderTotal = r.data.data.total
          } else {
            vm.$toast(r.data.message)
          }
        })
        .catch(e => {
          console.error(e)
        })
    }
  }
}
</script>

<style lang="scss" scoped>
@import 'static/styles/color.scss';

.banner {
  > .top {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 15px;
    > .logo {
      width: 36px;
      height: 36px;
      display: block;
      border-radius: 50%;
      margin-right: 10px;
    }
    > .shop-name {
      font-size: 15px;
      flex-grow: 1;
    }
    > .date-filter-picker {
      padding-right: 10px;
      .value {
        position: relative;
        font-size: 12px;
        /* &::after {
          content: '';
          display: block;
          width: 8px;
          height: 8px;
          box-sizing: border-box;
          border-top: 4px solid $white;
          border-bottom: 4px solid transparent;
          border-left: 4px solid transparent;
          border-right: 4px solid transparent;
          position: absolute;
          right: -10px;
          top: 50%;
          transform: translateY(calc(2px - 50%));
        } */
      }
    }
  }
  > .panel {
    display: flex;
    flex-flow: row wrap;
    align-items: center;
    justify-content: space-between;
    font-size: 15px;
    > .block {
      width: 50%;
      display: inline-flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      padding: 0 15px;
      > .title {
        font-size: 12px;
        margin-bottom: 5px;
        > .small-icon {
          width: 20px;
          height: 20px;
          transform: translateY(5px);
        }
      }
      &:first-child {
        border-right: 1px solid $light-white;
        border-bottom: 1px solid $light-white;
        padding-bottom: 10px;
      }
      &:nth-child(2) {
        border-bottom: 1px solid $light-white;
        padding-bottom: 10px;
      }
      &:nth-child(3) {
        border-right: 1px solid $light-white;
        padding-top: 10px;
      }
      &:last-child {
        padding-top: 10px;
      }
    }
  }
}

.filter {
  padding: 15px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  > .filter-picker {
    width: 50%;
    text-align: center;
    .value {
      font-size: 15px;
      color: $blue;
    }
  }
}
.statistics {
  text-align: center;
  font-size: 12px;
  .blue {
    color: $blue;
  }
}
.chart-wrap {
  padding: 0 15px;
  width: 100%;
  height: 300px;
}
</style>
